package com.yw.mq.example.m06_oneway;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

import static com.yw.mq.core.MqConstant.DEFAULT_CONSUMER_GROUP;
import static com.yw.mq.core.MqConstant.NAME_SERVER_ADDR;

public class Consumer {
    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(DEFAULT_CONSUMER_GROUP);

        consumer.setNamesrvAddr(NAME_SERVER_ADDR);

        consumer.subscribe("order_topic", "*");
        
        consumer.setConsumeThreadMax(1);
        consumer.setConsumeThreadMin(1);
        consumer.setConsumeMessageBatchMaxSize(1);

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (int i = 0; i < list.size(); i++) {
                    MessageExt messageExt = list.get(i);
                    try {
                        System.out.println("收到消息：" + new String(messageExt.getBody()));
                    } catch (Exception e) {
                        System.out.println("消息消费失败：" + messageExt.getKeys());
                        consumeConcurrentlyContext.setAckIndex(i - 1);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
    }
}
